package com.njcb.ams.web.advice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.njcb.ams.pojo.bo.Head;
import com.njcb.ams.pojo.dto.standard.Response;
import com.njcb.ams.portal.SysBaseDefine;
import com.njcb.ams.factory.comm.DataBus;
import com.njcb.ams.service.DataDicService;
import com.njcb.ams.support.exception.ExceptionUtil;

/**
 * mvc返回适配，统一处理数据字典加载
 * 
 * @author liuyanlong
 *
 */
@Order(1)
@ControllerAdvice
public class DataDictionaryBodyAdvice implements ResponseBodyAdvice<Object> {
	private static final Logger logger = LoggerFactory.getLogger(DataDictionaryBodyAdvice.class);

	@Override
	@SuppressWarnings("unchecked")
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType contentType, Class<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		Class<?> rtClass = returnType.getMethod().getReturnType();
		if (!rtClass.isAssignableFrom(Map.class) && !Response.class.isAssignableFrom(rtClass)) {
			return body;
		}
		if (request instanceof ServletServerHttpRequest && (body instanceof Map || body instanceof Response)) {
			Head requestHead = DataBus.getObject(Head.class);
			if(null == requestHead){
				return body;
			}
			Map<String, Map<String, String>> dataDicMap = new HashMap<String, Map<String, String>>();
			try {
				Map<String, List<String>> ret = null;
				if (null != requestHead) {
					if(null != requestHead.getDataDic()){
						requestHead.getDataDic().forEach((dataType, value) -> {
							dataDicMap.put(dataType, DataDicService.getDataType(dataType));
						});
					}

					if(body instanceof Map){
						Map<String, Object> modelMapBody = (Map<String, Object>) body;
						Map<String, Object> extValues = new HashMap<String, Object>();
						extValues.put(SysBaseDefine.REQ_PARAM_DICMAP, dataDicMap);
						extValues.put(SysBaseDefine.REQ_PARAM_DICLIST, ret);
						modelMapBody.put("extValues", extValues);
					}else if(body instanceof Response){
						Response modelMapBody = (Response) body;
						modelMapBody.putExtField(SysBaseDefine.REQ_PARAM_DICMAP, dataDicMap);
						modelMapBody.putExtField(SysBaseDefine.REQ_PARAM_DICLIST, ret);
					}
				}
				
				if(body instanceof HashMap){
					Map<String, Object> modelMapBody = (Map<String, Object>) body;
					Map<String, Object> extValues = new HashMap<String, Object>();
					extValues.put(SysBaseDefine.REQ_PARAM_DICMAP, dataDicMap);
					extValues.put(SysBaseDefine.REQ_PARAM_DICLIST, ret);
					modelMapBody.put("extValues", extValues);
				}else if(body instanceof Response){
					Response modelMapBody = (Response) body;
					modelMapBody.putExtField(SysBaseDefine.REQ_PARAM_DICMAP, dataDicMap);
					modelMapBody.putExtField(SysBaseDefine.REQ_PARAM_DICLIST, ret);
				}
			} catch (Exception e) {
				logger.error("\nJSON解析错误:JSON字符串为[{}]", requestHead.toString());
				logger.error(e.getMessage(), e);
				ExceptionUtil.throwAppException(e);
			}
		}
		return body;
	}

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		// 判断Controller返回值是否Map，如果是则返回true执行此处理，否则不处理
		return true;
	}

}
